<template>
	<div class="container">
		<h2 style="text-align: center;margin-bottom: 30px;">{{ dataInfo.supplier_name }}</h2>
		<a-descriptions size="middle" title="供应商评分" bordered>
			<a-descriptions-item label="验收供应商得分">
				<a-score v-if="dataInfo.ys_total_score" v-model:score="dataInfo.ys_total_score" :min="1" :max="100" :disabled="true" :line-feed="true" />
				<span v-else class="red">暂无评分</span>
			</a-descriptions-item>
			<a-descriptions-item label="季度供应商得分">
				<a-score v-if="dataInfo.quarter_total_score" v-model:score="dataInfo.quarter_total_score" :min="1" :max="100" :disabled="true" :line-feed="true" />
				<span v-else class="red">暂无评分</span>
			</a-descriptions-item>
			<a-descriptions-item label="年度供应商得分">
				<a-score v-if="dataInfo.year_total_score" v-model:score="dataInfo.year_total_score" :min="1" :max="100" :disabled="true" :line-feed="true" />
				<span v-else class="red">暂无评分</span>
			</a-descriptions-item>
		</a-descriptions><br />
		<a-descriptions v-permission="'218'" size="middle">
			<a-descriptions-item label="本季度评价" :span="3">
				<a-button v-if="!dataInfo.quarter_appraise" type="primary" ghost danger @click="quarterAppraise(false, [])">去评分</a-button>
				<a-button v-else type="primary" ghost @click="quarterAppraise(true, dataInfo.quarter_appraise)">已评价</a-button>
			</a-descriptions-item>
		</a-descriptions>
		<a-descriptions v-permission="'221'" size="middle">
			<a-descriptions-item label="本年度评价" :span="3">
				<a-button v-if="!dataInfo.year_appraise" type="primary" ghost danger @click="yearAppraise(false, [])">去评分</a-button>
				<a-button v-else type="primary" ghost @click="yearAppraise(true, dataInfo.year_appraise)">已评价</a-button>
			</a-descriptions-item>
		</a-descriptions>
		<h3 style="margin: 10px 0;"><b>评分明细</b></h3>
		<a-form ref="searchRef" :model="searchState" @finish="current=1;loading=true;initData()">
			<a-row :gutter="20">
				<a-col :span="6">
					<a-form-item label="选择类型">
						<a-radio-group v-model:value="searchState.appraise_type" @change="current=1;loading=true;initData()">
							<a-radio-button v-for="option of typeOptions" :key="option.value" :value="option.value">{{ option.label }}</a-radio-button>
						</a-radio-group>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="时间范围">
						<a-range-picker v-model:value="searchState.date_range" allow-clear value-format="YYYY-MM-DD" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item>
						<a-space>
							<a-button type="primary" html-type="submit">
								<search-outlined />搜索
							</a-button>
							<a-button type="link" @click="handleExport">
								<export-outlined />导出
							</a-button>
						</a-space>
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<div class="mt-2">
			<a-table :columns="innerColumns" :scroll="tableScroll" :data-source="dataSource" :pagination="pagination" @change="initData">
				<template #bodyCell="{ column, record }">
					<template v-for="(item, i) in record" :key="i">
						<span v-if="column.dataIndex === item.stats_id">
							<template v-if="['APPRAISE_DAILY', 'APPRAISE_QUARTER', 'APPRAISE_YEAR'].includes(item.stats_code)">
								<a-score v-model:score="item.stats_data" :min="1" :max="parseInt(item.stats_max_score)" :disabled="true" :line-feed="true" />
							</template>
							<template v-else-if="item.stats_code === 'APPRAISE_COMMENT'">
								{{ item.stats_data }}
							</template>
							<template v-else-if="item.stats_code === 'APPRAISE_FILE_PATH'">
								<a v-if="item.stats_data" :href="JSON.parse(item.stats_data || '[]')[0]?.url" target="_blank">{{ JSON.parse(item.stats_data || '[]')[0]?.name }}</a>
							</template>
						</span>
					</template>
					<template v-if="column.dataIndex === 'operation'">
						<a-space>
							<a-button v-permission="69" type="link" @click="appraise(record)">
								<diff-outlined />查看
							</a-button>
						</a-space>
					</template>
				</template>
			</a-table>
		</div>
		<a-modal title="评分" :visible="visible" :confirm-loading="modalLoading" ok-text="确定" :ok-button-props="{ disabled: formState.readonly }" cancel-text="取消" @ok="saveAppraise" @cancel="visible = false;">
			<a-form ref="formRef" :model="formState" v-bind="{ labelCol: { span: 6 }, wrapperCol: { span: 16 }, }">
				<a-form-item label="类别" name="appraise_type" :rules="[{ required: true, message: '请选择评分类别' }]">
					<a-select v-model:value="formState.appraise_type" placeholder="请选择评分类别" :options="typeOptions" option-filter-prop="label" disabled></a-select>
				</a-form-item>
				<template v-for="(item, i) in formState.appraises" :key="formState.random_id + '_' +item.stats_id">
					<a-form-item v-if="['APPRAISE_QUARTER', 'APPRAISE_YEAR'].includes(item.stats_code)" :label="item.stats_name" :name="['appraises', i, 'stats_data']" :rules="{required:true, message:'请打星评分'}">
						<a-score v-model:score="item.stats_data" :min="1" :max="parseInt(item.stats_max_score)" :disabled="formState.readonly" />
					</a-form-item>
					<template v-else-if="item.stats_code === 'APPRAISE_COMMENT'">
						<a-form-item v-if="!formState.readonly" label="快捷评语">
							<a-select
								v-model:value="formState.content_template"
								style="width: 100%"
								:options="contentTemplateOptions"
								placeholder="内容模版"
								@change="(data) => item.stats_data = contentTemplateOptions.find((d) => d.value === data)?.label"
							></a-select>
						</a-form-item>
						<a-form-item :label="item.stats_name" :name="['appraises', i, 'stats_data']" :rules="{required:true, message:'请输入评语'}">
							<a-textarea v-model:value="item.stats_data" :auto-size="{minRows:4, maxRows:6}" allow-clear :disabled="formState.readonly" />
						</a-form-item>
					</template>
					<a-form-item v-else-if="item.stats_code === 'APPRAISE_FILE_PATH'" :label="item.stats_name" :name="['appraises', i, 'stats_data']" :rules="{required: fileRequired, message:'请上传附件'}">
						<a-upload v-if="formState.readonly" v-model:file-list="item.stats_data" disabled name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{Authorization:`Bearer ${proxy.$cookies.get('token')}`}" @change="fileChangeUpload(item, $event)">
							<a-button>
								<template v-if="file_uploading">
									<loading-outlined />上传中...
								</template>
								<template v-else>
									<import-outlined />上传附件
								</template>
							</a-button>
						</a-upload>
						<a-upload v-else v-model:score="item.stats_data" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{Authorization:`Bearer ${proxy.$cookies.get('token')}`}" @change="fileChangeUpload(item, $event)">
							<a-button>
								<template v-if="file_uploading">
									<loading-outlined />上传中...
								</template>
								<template v-else>
									<import-outlined />上传附件
								</template>
							</a-button>
						</a-upload>
					</a-form-item>
				</template>
			</a-form>
		</a-modal>
		<a-row :gutter="20">
			<a-col :span="24" class="py-4 text-center">
				<a-space>
					<a-button @click="closeTab('/supplier')">
						<close-outlined />关闭
					</a-button>
				</a-space>
			</a-col>
		</a-row>
	</div>
</template>
<script setup>
import { computed, getCurrentInstance, inject, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { post } from "@/utils/index.js";
import { usePagination } from "vue-request";
import { CloseOutlined, DiffOutlined, EditOutlined, ExportOutlined } from "@ant-design/icons-vue";
import { AScore } from "@/components/index.js";
import { baseURL } from "@/utils/request.js";
const route = useRoute();
const router = useRouter();
const id = computed(() => route.params.id);
const searchRef = ref();
const dataInfo = ref({});
const { proxy } = getCurrentInstance();
const typeOptions = [
	{
		value: 1,
		label: "验收评分"
	},
	{
		value: 2,
		label: "季度评分"
	},
	{
		value: 3,
		label: "年度评分"
	}
];
const appraiseStats = ref([]);
post("dictionary", { root_code: "APPRAISE_STATS" }).then(data => {
	appraiseStats.value = data;
});
const contentTemplateOptions = ref([]);

const searchState = reactive({
	appraise_type: typeOptions[0].value
});
const innerColumns = computed(() => {
	const columns = [{
		title: "序号",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left",
		customRender: ({ text, record, index, column }) => {
			return index + 1;
		}
	}];
	if (searchState.appraise_type === 1) {
		for (const stats of appraiseStats.value) {
			if (!['APPRAISE_DAILY', 'APPRAISE_COMMENT', 'APPRAISE_FILE_PATH'].includes(stats.code)) continue;
			columns.push({
				title: stats.name,
				dataIndex: stats.id,
				width: 200,
				align: "left",
			});
		}
	} else if (searchState.appraise_type === 2) {
		for (const stats of appraiseStats.value) {
			if (!['APPRAISE_QUARTER', 'APPRAISE_COMMENT', 'APPRAISE_FILE_PATH'].includes(stats.code)) continue;
			columns.push({
				title: stats.name,
				dataIndex: stats.id,
				width: 200,
				align: "left",
			});
		}
	} else if (searchState.appraise_type === 3) {
		for (const stats of appraiseStats.value) {
			if (!['APPRAISE_YEAR', 'APPRAISE_COMMENT', 'APPRAISE_FILE_PATH'].includes(stats.code)) continue;
			columns.push({
				title: stats.name,
				dataIndex: stats.id,
				width: 200,
				align: "left",
			});
		}
	}
	columns.push({
		title: '时间',
		dataIndex: "create_time",
		width: 160,
		align: "left",
		fixed: "right",
		customRender: ({ text, record, index, column }) => {
			return record[0]?.create_time;
		}
	});
	columns.push({
		title: "评分人",
		dataIndex: "appraiser",
		width: 120,
		align: "left",
		fixed: "right",
		customRender: ({ text, record, index, column }) => {
			return record[0]?.appraiser?.fullname;
		}
	})
	if (searchState.appraise_type === 1) {
		columns.push(
			{
				title: "项目名称",
				dataIndex: "supplyOrder",
				width: 120,
				align: "left",
				fixed: "right",
				customRender: ({ text, record, index, column }) => {
					return record[0]?.supplyOrder?.project?.name
				}
			}, {
				title: "操作",
				dataIndex: "operation",
				width: 80,
				align: "left",
				fixed: "right",
			}
		);
	}
	return columns;
})
const visible = ref(false);
const modalLoading = ref(false);
const formRef = ref();
const formState = ref({});
const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));
onMounted(() => {
	getInfo();
})
const getInfo = async () => {
	const appraise = await post("appraise/info", { supplier_id: id.value });
	dataInfo.value = appraise;
}
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));
const { data, loading, run, current, pageSize, total } = usePagination(async params => post("appraise", { supplier_id: id.value, ...params, ...searchState }), {
	defaultParams: [
		{
			page_size: 10
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});
const dataSource = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		return d;
	})
);
const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	if (searchState.date_range?.length) {
		filters.start_time = filters.date_range[0];
		filters.end_time = filters.date_range[1]
	}
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
const quarterAppraise = (readonly, appraises) => {
	visible.value = true;
	formState.value = {
		appraise_type: 2,
		random_id: Date.now(),
		readonly: !!readonly,
		appraises,
	};
	post("dictionary", { root_id: 1409 }).then(data => {
		contentTemplateOptions.value = data;
	});
	if (!appraises.length) {
		for (const item of appraiseStats.value) {
			if (!['APPRAISE_QUARTER', 'APPRAISE_COMMENT', 'APPRAISE_FILE_PATH'].includes(item.code)) continue;
			formState.value.appraises.push({
				stats_id: item.id,
				stats_name: item.name,
				stats_code: item.code,
				stats_data: item.code === 'APPRAISE_FILE_PATH' ? [] : null,
				stats_max_score: item.memo
			})
		}
	} else {
		for (const appraise of appraises) {
			if (['APPRAISE_FILE_PATH'].includes(appraise.stats_code)) {
				appraise.stats_data = JSON.parse(appraise.stats_data);
			}
		}
	}
};
const file_uploading = ref(false);
const fileChangeUpload = (item, { file }) => {
	if (file.status === "done") {
		item.stats_data = [{
			name: file.name,
			url: file.response.data.url
		}];
		file_uploading.value = false;
		proxy.$message.success("附件上传成功");
	}
	item.stats_data = item.stats_data.filter((item) => item.url)
};
const yearAppraise = (readonly, appraises) => {
	visible.value = true;
	formState.value = {
		appraise_type: 3,
		random_id: Date.now(),
		readonly: !!readonly,
		appraises,
	};
	post("dictionary", { root_id: 1410 }).then(data => {
		contentTemplateOptions.value = data;
	});
	if (!appraises.length) {
		for (const item of appraiseStats.value) {
			if (!['APPRAISE_YEAR', 'APPRAISE_COMMENT', 'APPRAISE_FILE_PATH'].includes(item.code)) continue;
			formState.value.appraises.push({
				stats_id: item.id,
				stats_name: item.name,
				stats_code: item.code,
				stats_data: item.code === 'APPRAISE_FILE_PATH' ? [] : null,
				stats_max_score: item.memo
			})
		}
	} else {
		for (const appraise of appraises) {
			if (['APPRAISE_FILE_PATH'].includes(appraise.stats_code)) {
				appraise.stats_data = JSON.parse(appraise.stats_data);
			}
		}
	}
};

// 评分为差时附件必填
const fileRequired = computed(() => {
	let required = false;
	for (const appraise of formState.value.appraises) {
		if (appraise.stats_code !== 'APPRAISE_QUARTER') continue;
		if (!appraise.stats_data) {
			required = true;
			break;
		}
		if (appraise.stats_data <= Math.floor(appraise.stats_max_score / 3)) {
			required = true;
			break;
		}
	}
	return required;
})
const appraise = record => {
	router.push(`/yanshoulog/info/${record[0]?.supply_order_id}?appraise=1`);
}

const handleExport = () => {
	post("appraise", {
		supplier_id: id.value,
		submit: 'export',
		...searchState,
		...(searchState.date_range?.length ? {
			start_time: searchState.date_range[0],
			end_time: searchState.date_range[1],
		} : {}),
	}).then(({ url }) => {
		if (url) window.location.href = url;
	})
}
const saveAppraise = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			const comment = formState.value.appraises.filter(item => item.stats_code === 'APPRAISE_COMMENT')[0].stats_data;
			if (comment.length < 50) {
				proxy.$message.error("评价内容不能少于50个字");
				return;
			}
			modalLoading.value = true;
			const params = {
				supplier_id: id.value,
				appraise_type: formState.value.appraise_type,
				appraises: formState.value.appraises,
			};
			post("appraise/save", params)
				.then(() => {
					proxy.$message.success("评价成功", 1);
					visible.value = false;
					modalLoading.value = false;
					initData();
					getInfo();
				})
				.catch(err => {
					proxy.$message.error(err);
					modalLoading.value = false;
				});
		})
}
const closeTab = inject("closeTab");
</script>
<style scoped lang="scss">
.container {
  background: #fff;
  padding: 20px;

  :deep(.ant-table-cell) .ant-form-item {
    margin-bottom: 0;

    .ant-form-item-explain {
      position: absolute;
      bottom: -24px;
    }
  }

  :deep(.ant-form-item) {
    margin-bottom: 0;
  }
}
.red {
  color: red;
}
</style>